package com.hongyi.common.saToken.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import com.hongyi.common.saToken.properties.PermissionProperties;
import com.hongyi.common.saToken.service.SaPermissionImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * sa-token 配置
 *
 * @author DingHao
 */
@Slf4j
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Autowired
    private PermissionProperties permissionProperties;

    public SaTokenConfig() {
        log.info("加载SaTokenConfig配置");
    }

    /**
     * Sa-Token 整合 jwt (简单模式)
     */
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    /**
     * 自定义注解权限验证
     */
    @Bean
    public StpInterface stpInterface() {
        return new SaPermissionImpl();
    }

    /**
     * 注册sa-token的拦截器
     *
     * @param registry InterceptorRegistry 是Spring提供的一个接口，用来注册拦截器。
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册路由拦截器，自定义验证规则
        registry.addInterceptor(new SaInterceptor(handed -> SaRouter
                        .match("/**")
                        .check(() -> {
                            // 检查是否登录 是否有token
                            StpUtil.checkLogin();
                        }))).addPathPatterns("/**")
                .excludePathPatterns(permissionProperties.getExcludes());// 排除不需要拦截的路径

    }





}
